---
import {
    POST_INIT_MESSAGE_START,
    POST_INIT_MESSAGE_END,
    LIBRARY_INIT_SELECTOR,
} from '@components/example-runner/constants';
interface Props {
    pageName: string;
    exampleName: string;
    nonce?: string;
}

const { pageName, exampleName, nonce } = Astro.props as Props;
const initSelector = LIBRARY_INIT_SELECTOR;
---

<Fragment set:html={POST_INIT_MESSAGE_START} />
<script
    nonce={nonce}
    define:vars={{
        pageName,
        exampleName,
        initSelector,
    }}
>
    const checkInit = function () {
        if (document.querySelector(initSelector)) {
            const loadedEvent = {
                type: 'init',
                pageName,
                exampleName,
            };
            window.parent?.postMessage(loadedEvent);
        } else {
            requestAnimationFrame(() => checkInit());
        }
    };

    checkInit();
</script>
<Fragment set:html={POST_INIT_MESSAGE_END} />
